var client_messages = 1;
var client_id_str = "-";

function getClientId(s) {

    s.on('upload', function (data, flags) {
        var packet_type_flags_byte = data.charCodeAt(0);
        // s.warn("MQTT packet type+flags = " + packet_type_flags_byte.toString());
        if ( packet_type_flags_byte >= 16 && packet_type_flags_byte < 32 ) {
            // Calculate remaining length with variable encoding scheme
            var payload_offset= 12 ;
            var client_id_len_msb = data.charCodeAt(payload_offset).toString(16);
            var client_id_len_lsb = data.charCodeAt(payload_offset + 1).toString(16);
            if ( client_id_len_lsb.length < 2 ) client_id_len_lsb = "0" + client_id_len_lsb;
            var client_id_len_int = parseInt(client_id_len_msb + client_id_len_lsb, 16);
            
            s.log("MQTT clientId length = " + client_id_len_int.toString());
            client_id_str = data.substr(14, client_id_len_int);
            s.log("ClientId value  = " + client_id_str);
        } 

        if (data.length || flags.last) {
            s.done();
        }
    });
}


function mqttRoute(s) {
    var route =  client_id_str.substring(0,5)=="YZ-DB" ? "mqtt_b_back" : "mqtt_a_back";
    s.log("route is " + route);
    return route;
}

export default {getClientId, mqttRoute}